package jwt

import (
	"cloud-storage/global"
	"cloud-storage/lib"
	"errors"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

var (
	TokenExpired     = errors.New("令牌已过期")
	TokenNotValidYet = errors.New("令牌尚未激活")
	TokenMalformed   = errors.New("不是令牌")
	TokenInvalid     = errors.New("无法处理此令牌")
)

type CustomClaims struct {
	Phone      string
	BufferTime int64
	jwt.RegisteredClaims
}

// CreateClaims 创建一个Claims
func CreateClaims(phone string) CustomClaims {
	claim := CustomClaims{
		Phone:      phone,
		BufferTime: lib.JWTSetting.BufferTime,
		RegisteredClaims: jwt.RegisteredClaims{
			// 签名生效时间
			NotBefore: jwt.NewNumericDate(time.Now().Add(-time.Second * 1000)),
			// 过期时间 7天  配置文件中获取
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * lib.JWTSetting.ExpiresTime)),
			// 签名的发行者，也是从配置文件中获取
			Issuer: lib.JWTSetting.Issuer,
		},
	}
	return claim
}

// CreateToken 创建一个token
func CreateToken(claims CustomClaims) (string, error) {
	// 使用指定的签名方法创建签名对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 使用指定的secret签名并获得完整的编码后的字符串token
	return token.SignedString([]byte(lib.JWTSetting.SigningKey))
}

// ParseToken 解析token
func ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return []byte(lib.JWTSetting.SigningKey), nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	// 校验token
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, TokenInvalid
}

// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func CreateTokenByOldToken(oldToken string, claims CustomClaims) (string, error) {
	v, err, _ := global.GVA_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
		return CreateToken(claims)
	})
	return v.(string), err
}
